package com.cloudcc.mobile.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Environment;

public class UploadImgManyClient {
	@SuppressLint("SimpleDateFormat")
	public static String sendMany(String[] uploadFiles, String actionUrl){
		try {
			Tools.i("duozhangtupian", "--------UploadImgManyClient--开始----------");
			for (int i = 0; i < uploadFiles.length; i++) {
				File file = new File(uploadFiles[i]);
				if (!file.exists() || !file.isFile()) {
					return null;
				}
			}
			Tools.i("duozhangtupian", "--------UploadImgManyClient-----第一个for循环结束--");
			/**			 * 第一部分			 */
			URL urlObj = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
			/**			 * 设置关键值			 */
			con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存
			con.setConnectTimeout(40000);//超时时间
			con.setReadTimeout(40000);//设置从主机读取数据超时（单位：毫秒）
			// 设置请求头信息
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			// 设置边界
			String BOUNDARY = "----------" + System.currentTimeMillis();

			con.setRequestProperty("Content-Type", "multipart/mixed; boundary="
					+ BOUNDARY);
			// con.setRequestProperty("content-type",
			// "multipart/form-data; boundary=" + BOUNDARY);
			// con.setRequestProperty("content-type", "text/html");
			// 请求正文信息
			OutputStream out = new DataOutputStream(con.getOutputStream());
			for (int i = 0; i < uploadFiles.length; i++) {
				String filePath=uploadFiles[i];
				Bitmap bitmap=ImageUtils.getImg(filePath,480f,800f);
				byte[] imagebyte=ImageUtils.compressBitmap(bitmap,100f);
				SimpleDateFormat formatter=new SimpleDateFormat ("yyyyMMddHHmmss");     
				Date curDate= new Date(System.currentTimeMillis());//获取当前时间     
				String time=formatter.format(curDate);
				String picPath=ImageUtils.SaveImage(time+".jpg", imagebyte);
				File file = new File(picPath);
				if (!file.exists() || !file.isFile()) {
					return null;
				}
				StringBuilder sb = new StringBuilder();
				sb.append("--"); // ////////必须多两道线
				sb.append(BOUNDARY);
				sb.append("\r\n");
				sb.append("Content-Disposition: form-data;name=\"file" + i + 1
						+ "\";filename=\"" + file.getName() + "\"\r\n");
				sb.append("Content-Type:application/octet-stream\r\n\r\n");
				byte[] head = sb.toString().getBytes("utf-8");
				// 获得输出流
				out.write(head);
				//OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");

				// 文件正文部分
				DataInputStream in = new DataInputStream(new FileInputStream(file));
				int bytes = 0;
				byte[] bufferOut = new byte[1024];
				while ((bytes = in.read(bufferOut)) != -1) {
					out.write(bufferOut, 0, bytes);
				}
				out.write("\r\n".getBytes()); //多个文件时，二个文件之间加入这个
				in.close();
				//删除这个文件
				String imagepath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/CloudCC/Download/"+time+".jpg";
				FileUtil.deleteFile(imagepath);
			}
			Tools.i("duozhangtupian", "--------UploadImgManyClient-----第二个for循环结束--");
			// 第一部分：
			// 结尾部分
			byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
			out.write(foot);
			out.flush();
			out.close();
			/**
			 * 读取服务器响应，必须读取,否则提交不成功
			 */
			// return con.getResponseCode();
			int res= con.getResponseCode();
			if(res!=200){
				return null;
			}
			Tools.i("duozhangtupian", "--------UploadImgManyClient--res-----返回的响应码-----"+res);
			/**
			 * 下面的方式读取也是可以的
			 */
			// 定义BufferedReader输入流来读取URL的响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream(), "UTF-8"));
			StringBuilder sbString = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sbString.append(line + "\n");  
			}
			reader.close(); 
			con.disconnect();  
			Tools.i("duozhangtupian", "---------7.15返回的参数--结束------------"+sbString.toString());
			return sbString.toString();
		} catch (Exception e) {
			Tools.i("duozhangtupian", "---------7.16返回的参数------联网超时--------");
			Tools.i("outtime", "ConnectTimeoutException");
			Tools.handle(e);
			return "null";
		}
	}
}
